<?php

namespace app\api\controller;

use app\common\model\Topic as T;
use app\common\model\User;
use app\common\model\Post;
use think\facade\Db;

class Topic extends ApiBase {

	// 不需要验证token的方法
	protected $middleware = [
		'app\api\middleware\Auth' => ['except' => ['classList', "list", "detail","topicClassTop","userJoinTopic","search","userNum","hot","classTopicAreImg"]],
	];

	//圈子分类
	public function classList() {
		$list = Db::name("category")->select();
		return success($list);
	}

	//删除圈子分类
	public function cateDel() {
		$id = input("id");
		$res = Db::name("category")->where("cate_id", $id)->delete();
		if ($res) {
			return notice("删除成功");
		}
		return error("删除失败");
	}
	//修改圈子分类
	public function cateAddEdit() {
		$id = input("cate_id");
		$cateName = input("cate_name");
		$coverImage = input("cover_image");
		if (empty($id)) {
			$data["cate_name"] = $cateName;
			$data["cover_image"] = $coverImage;
			$res = Db::name("category")->insert($data);
			if ($res) {
				return notice("添加成功");
			}
			return error("添加失败");
		} else {
			$data["cate_id"] = $id;
			$data["cate_name"] = $cateName;
			$data["cover_image"] = $coverImage;
			$res = Db::name("category")->update($data);
			if ($res) {
				return notice("修改成功");
			}
			return error("修改失败");
		}
	}
	//圈子列表-状态为1的圈子
	public function list() {
		$classId = input("class_id");
		$keyword = input("keyword");
		$topType = input("top_type");

		$where[] = ["topic.status","=",0]; //正常状态下的圈子
		if ($classId) {
			$where[] = ["cate_id","=",$classId];
		}

        if ($keyword) {
            $where[] = ["topic_name","like","%".$keyword."%"];
        }

		if ($topType) {
			$where[] = ["top_type","=",$topType];
		}

		$list = T::getList($where);

		return success($list);
	}

	//查询用户加入的圈子列表，不传uid时查询登录用户加入的圈子
    public function userJoinTopic(){
	    $uid = input("uid");

	    if(empty($uid)){
	        $uid = $this->uid;
        }

	    $topicIds = Db::name("user_topic")->where("uid",$uid)->column("topic_id");
	    $where[] = ["id","in",$topicIds];
        $list = T::getList($where,"id desc",100);
	    return success($list);
    }
    //所有圈子列表
    public function listAll() {
        $list = T::withJoin(["userInfo"])->order("id desc")->paginate(10)->each(function ($item){
            $topicId = $item["id"];
            $topicPostCount = Db::name("post")->where("topic_id",$topicId)->count();
            $topicUserCount = Db::name("user_topic")->where("topic_id",$topicId)->count();

            $item['post_count'] = $topicPostCount;
            $item['user_count'] = $topicUserCount;
            return $item;
        });
        return success($list);
    }
	//圈子详情
	public function detail() {
		$id = input("id");
		$uid = $this->uid;
		$detail = T::withJoin(["userInfo"])->find($id);

		$uids = Db::name("user_topic")->where("topic_id", $id)->column('uid');

		$where[] = ["uid", "=", $uid];
		$where[] = ["topic_id", "=", $id];

		$detail["is_join"] = false;

		$res = Db::name("user_topic")->where($where)->find();

		if ($res) {
			$detail["is_join"] = true;
		}

		$detail["is_admin"] = false;
        $isAdmin = Db::name("topic_admin")->where($where)->find();
        if($isAdmin){
            $detail["is_admin"] = true;
        }
        
		$detail["post_count"] = Db::name("post")->where("topic_id", $id)->count();
		$detail["user_count"] = Db::name("user_topic")->where("topic_id", $id)->count();
        $detail["discuss_list"] = Db::name("discuss")->where("topic_id", $id)->limit(5)->select();

        $adminUid = Db::name("topic_admin")->where("topic_id",$id)->column("uid");
        $detail["admin_list"] = User::order("update_time desc")->where("uid","in",$adminUid)->limit(9)->select($uids)->each(function ($item){
            $where["uid"] = $this->uid;
            $where["follow_uid"] = $item["uid"];

            $res1 = Db::name("follow")->where($where)->find();

            if ($res1) {
                $item["has_follow"] = 1; //互相关注
            } else {
                $item["has_follow"] = 0; //未关注
            }

            return $item;
        });

        $where2["uid"] = $this->uid;
        $where2["follow_uid"] = $detail["uid"];

        $res1 = Db::name("follow")->where($where2)->find();

        if ($res1) {
            $detail["userInfo"]["has_follow"] = 1; //互相关注
        } else {
            $detail["userInfo"]["has_follow"] = 0; //未关注
        }

        //置顶帖子
        $postIds = Db::name("topic_top")->where("topic_id",$id)->column("post_id");
        $detail["top_post"] = Db::name("post")->where("id","in",$postIds)->select();

		return success($detail);
	}

	public function user(){
		$id = input("id");
		$topicUid = Db::name("topic")->where("id",$id)->value("uid");
		$uids = Db::name("user_topic")->where("topic_id",$id)->column("uid");
		$list = User::order("update_time desc")->where("uid","<>",$topicUid)->where("uid","in",$uids)->paginate(20)->each(function($item) use ($id){
			$where["uid"] = $this->uid;
			$where["follow_uid"] = $item["uid"];

			$res1 = Db::name("follow")->where($where)->find();

			if ($res1) {
				$item["has_follow"] = 1; //互相关注
			} else {
				$item["has_follow"] = 0; //未关注
			}

			$isAdmin = Db::name("topic_admin")->where(["topic_id" => $id,"uid" => $item["uid"]])->find();
			if($isAdmin){
			    $item["is_admin"] = true;
            }else{
                $item["is_admin"] = false;
            }
		});

		return success($list);
	}

	//加入圈子
	public function joinTopic() {
		$uid = $this->uid;
		$topicId = input("id");

		$data["uid"] = $uid;
		$data["topic_id"] = $topicId;
		$data["create_time"] = time();
		$isjoinTopic = Db::name("user_topic")->where($data)->find();

		if ($isjoinTopic) {
			return error("您已加入圈子");
		}

		$res = Db::name("user_topic")->insert($data);

		if ($res) {
		    Db::name("topic")->where("id",$topicId)->inc("user_num")->update();
			return success("加入成功");
		}
		return error("未知错误");

	}

	//退出圈子
    public function userTopicDel() {

        $topicId = input("id");
        $uid = $this->uid;

        $where[] = ["uid", "=", $uid];
        $where[] = ["topic_id", "=", $topicId];

        $topicAdminUid = T::find($topicId)["uid"];

        if($topicAdminUid == $uid){
            return error("圈主不可退出圈子");
        }

        $res = Db::name("user_topic")->where($where)->delete();

        if ($res) {
            Db::name("topic")->where("id",$topicId)->dec("user_num")->update();
			return notice("已退出该圈子");
		}
		return error("操作失败");
	}

	//我创建的圈子
	public function myCreateTopic() {
		$uid = $this->uid;
		$where["topic.uid"] = $uid;

		$list = T::getList($where);

		return success($list);
	}

	//添加圈子
	public function topicAdd() {
		$uid = $this->uid;
		$data = input("post.");

		try {
			validate(\app\common\validate\Topic::class)->check($data);
		} catch (ValidateException $e) {
			return error($e->getError());
		}

		$data["uid"] = $uid;

		$topicNum = T::where("uid",$uid)->count();
		if($topicNum > 3 || $topicNum == 3){
		    return error("最多只能创建3个圈子");
        }

		$res = T::create($data);
		if ($res) {
		    $topicId = $res->id;
		    Db::name("user_topic")->insert(["uid" => $uid,"topic_id" =>$topicId,"create_time" => time()]); //创建成功后台圈主加入圈子
			return success(["id" =>$topicId], "创建成功");
		}
		return error("创建失败");
	}
	//修改圈子
	public function topicEdit() {
		$data = input("post.");
		try {
			validate(\app\common\validate\Topic::class)->check($data);
		} catch (ValidateException $e) {
			return error($e->getError());
		}

		$res = T::update($data);
		if ($res) {
			return notice("修改成功");
		}
		return error("修改失败");
	}
//	删除圈子
	public function topicDel() {
		$id = input("id");
		$res = T::destroy($id);
		if ($res) {
		    Db::name("user_topic")->where("topic_id",$id)->delete();//删除该圈子用户信息
		    Db::name("discuss")->where("topic_id",$id)->delete();//删除该圈子相应话题
			return notice("删除成功");
		}
		return error("删除失败");
	}

	//推荐圈子分类
	public function topicClassTop(){
	    $list = Db::name("category")->where("is_top",1)->select();
	    return success($list);
    }

	//更改圈子状态
	public function saveStatus(){
		$id = input("id");
		$status = input("status");
		$res = T::where("id",$id)->update(["status" => $status]);
		if($res){
			return notice("状态修改成功");
		}

		return error("状态修改失败");
	}

	//更改圈子首页推荐
	public function saveTop(){
		$id = input("id");
		$status = input("top_type");
		$res = T::where("id",$id)->update(["top_type" => $status]);
		if($res){
			return notice("修改成功");
		}

		return error("修改失败");
	}

	//统计信息
    public function statistics()
    {
        $topicId = input("id");
        $topic_uids = Db::name("user_topic")->where("topic_id",$topicId)->column("uid");

        $data['userCount'] = Db::name("user_topic")->where("topic_id",$topicId)->count();
        $data['postCount'] = Db::name("post")->where("topic_id",$topicId)->count();
        $data['disCount'] = Db::name("discuss")->where("topic_id",$topicId)->count();

        $data["last_month"] = Db::name('user_topic')->where("topic_id",$topicId)->whereMonth('create_time', 'last month')->count();
        $data["month"] = Db::name('user_topic')->where("topic_id",$topicId)->whereMonth('create_time')->count();
        $data["week"] = Db::name('user_topic')->where("topic_id",$topicId)->whereWeek('create_time')->count();
        $data["day"] = Db::name('user_topic')->where("topic_id",$topicId)->whereDay('create_time')->count();

        //近30天日期列表
        $monthDateList = getDateInterval(30, '-');
        $monthValue = [];

        foreach ($monthDateList as $item) {
            $date = Db::name('user')->where("uid","in",$topic_uids)->whereDay('create_time', $item)->count();
            array_push($monthValue, $date);
        }

        $month_data = [
            "categories" => $monthDateList,
            "series" => [
                [
                    "name" => "人数",
                    "data" => $monthValue
                ]
            ]
        ];

        //用户性别统计
        $unknown = Db::name('user')->where("uid","in",$topic_uids)->where("gender", 0)->count();
        $man = Db::name('user')->where("uid","in",$topic_uids)->where("gender", 1)->count();
        $female = Db::name('user')->where("uid","in",$topic_uids)->where("gender", 2)->count();

        $data["month_data"] = $month_data;
        $data["user_gender"] = [
            [
                "name" => "男性",
                "value" => $man,
            ],
            [
                "name" => "女性",
                "value" => $unknown,
            ],
            [
                "name" => "未知",
                "value" => $female,
            ]
        ];

        //用户城市分布
        $cityList = [];
        $userList = Db::name('user')->where("uid","in",$topic_uids)->cache(true, 3600)->column("province");

        foreach ($userList as $item) {
            if(!empty($item)){
                if(!in_array("$item",$cityList)){
                    array_push($cityList, $item);
                }
            }
        }

        $cityList = array_unique($cityList);

        $cityUserNum = [];
        foreach ($cityList as $item) {
            $count = Db::name('user')->where("uid","in",$topic_uids)->where('province', $item)->cache(true, 3600)->count();
            array_push($cityUserNum, $count);
        }
        $data["user_city"] = [
            "categories" => $cityList,
            "series" => [
                [
                    "name" => "人数",
                    "data" => $cityUserNum
                ]
            ]
        ];
        return success($data);
    }

    //获取圈子二维码
    public function qrCode(){
	    $id = input("id");
	    $wechat = new Wechat();

	    $qrCode = $wechat->makeQrCode("pages/topic/detail",$id,"topic_" .$id,"topic");

	    if($qrCode["success"]){
            return success($qrCode["src"]);

        }
	    return  error($qrCode["msg"]);
    }

    //圈子管理员列表
    public function adminUser(){
	    $id = input("id");
	    $uids = Db::name("topic_admin")->where("topic_id",$id)->column("uid");
	    $list = Db::name("user")->where("uid","in",$uids)->select();
	    return success($list);
    }

    //设置圈子管理员
    public function setAdmin(){
        $data = input("post.");
        $data["create_time"] = time();

        $res = Db::name("topic_admin")->insert($data);

        if($res){
            return notice("设置管理员成功");
        }
        return error("设置管理员失败");
    }

    //解除圈子管理员
    public function cancelAdmin(){
        $data = input("post.");

        $res = Db::name("topic_admin")->where($data)->delete();

        if($res){
            return notice("已解除管理员");
        }
        return error("解除管理员失败");
    }

    //搜索圈子
    public function search(){
        $keyword = input("keyword");
        $where[] = ["topic_name","like","%$keyword%"];
        $list = T::getList($where);
        return success($list);
    }

    //人数排序圈子（10个）
    public function hot(){
        $list = Db::name("topic")->where("id","not in",[1,271,272])->order("user_num desc")->limit(10)->select();
        return success($list);
    }

    //矫正圈子人数(管理员自用)
    public function userNum(){
	    $list = Db::name("topic")->select()->toArray();

	    foreach ($list as $item){
	        $userNum = Db::name("user_topic")->where("topic_id",$item["id"])->count();
            Db::name("topic")->where("id",$item["id"])->update(["user_num" => $userNum]);
        }
    }

    //圈子列表，显示最新三条帖子图片
    public function classTopicAreImg(){
        $cateId = input("class_id");


        $where[] = ["user_num",">",10]; //只查询圈子人数大于10
        if($cateId > 0){
            $where[] = ["cate_id","=",$cateId];
        }

        $list = Db::name("topic")->where($where)->order("id desc")->paginate(10)->each(function ($item){

            $imgList = [];


            $postList = Post::where("type",'=',1) //只查询图文帖子
            ->where("media","<>","[]")
                ->where("topic_id","=",$item["id"])
                ->order( "id desc")
                ->field("media")
                ->limit(3)
                ->select();

            foreach ($postList as $item2){
                array_push($imgList,$item2["media"][0]);
            }

            $item["img_list"] = $imgList;
            $item["post_num"] = Db::name("post")->where("topic_id","=",$item["id"])->count();

            return $item;

        });

        return success($list);
    }
}